import { defineStore } from "pinia";
import { ref } from "vue";
import { menu_list } from "../menu.ts";
import router from "../router.ts";
import { btnValue } from "../store/task/top";
const task_store = btnValue();
interface menu_item {
  title: string;
  path: string;
  icon: string;
  flag: boolean;
  children: menu_item[];
}

export const useIndexStore = defineStore("Index", () => {
  const menu_item = ref(menu_list[0]);
  const menu_lists = ref(menu_list);
  const new_page = ref(null);
  const menu_arr = ref([
    { title: "首页", icon: "/home.svg", active: true, path: "" },
  ]);
  const menu_Array = (item: any) => {
    let exists = menu_arr.value.some(
      (el) => el.title === item.title && el.path === item.path
    );
    if (!exists) {
      item.id = new Date().getTime();
      menu_arr.value.push({ ...item, active: false });
      console.log(`Added item: ${item.title}`);
    } else {
    }
    tabs_toggle(item);
    task_store.currentPath(item.path);
    router.push(`/home${item.path}`);
  };
  const menu_flag = (items: any) => {
    menu_lists.value.map((item) => {
      item.children.map((it) => {
        if (it.title === items.title && it.flag !== undefined) {
          it.flag = !it.flag;
        } else {
          if (it.title === items.title && it.flag === undefined) {
            menu_Array(it);
          }
        }
      });
    });
    menu_lists.value = [...menu_lists.value];
  };
  const tabs_toggle = (menu: menu_item) => {
    for (let item of menu_arr.value) {
      item.active = item.title === menu.title;
    }
    if (menu.path) {
      router.push(`/home${menu.path}`);
      task_store.currentPath(menu.path);
    } else {
      router.push(`/home`);
    }
  };
  const tabs_remove = (menu: menu_item) => {
    menu_arr.value = menu_arr.value.filter((item) => item.title !== menu.title);
    let num = 0;
    for (let menu of menu_arr.value) {
      if (menu.active) {
        num++;
        break;
      }
    }
    if (num > 0) {
      return;
    } else {
      menu_arr.value[0].active = true;
      router.push("/home");
    }
  };
  const tree_data = ref([
    {
      label: "智企科技开发团队",
      children: [
        {
          label: "团队1",
          children: [{ label: "张思" }, { label: "王五" }, { label: "魔1" }],
        },
      ],
    },
  ]);
  return {
    menu_item,
    menu_flag,
    menu_Array,
    menu_arr,
    menu_lists,
    tabs_toggle,
    tabs_remove,
    new_page,
    tree_data,
  };
});
